import {
	findById,
	getCateTree,
	getBrand,
	getCateParam
} from '@/api/product';
const state = {
	proInfo: null,
	cateList: [],
	brandList: [],
	cateParam: [],
	specInfo: {},
	proImgs:[]
}

const actions = {
	async getProInfo({
		commit,
		dispatch
	}, pload) {
		const res = await findById(pload);
		if (res.success && res.data) {
			commit('setProInfo', res.data);
			dispatch('getCateParamAction', {
				id: res.data.categoryId
			})
			if (res.data.productSpecs && res.data.productSpecs[0]) {
				const spec = res.data.productSpecs[0];
				commit('setSpecInfo', {
					shopPrice: spec.shopPrice,
					grossWeight: spec.grossWeight,
					netWeight: spec.netWeight,
				});
			} else {
				commit('setSpecInfo', {
					shopPrice: 0,
					grossWeight: 0,
					netWeight: 0,
				});
			}
			if(res.data.productImages && res.data.productImages.length){
				const list = res.data.productImages.map(item=>{
					return {
						...item,
						url:item.largeImage
					}
				})
				commit('setProImgs', list);
			}
		}
	},
	async getCateTreeAction({
		commit
	}) {
		const res = await getCateTree();
		if (res.success && res.data) {
			commit('setCateList', res.data);
		}
	},
	async getBrandAction({
		commit
	}) {
		const res = await getBrand();
		if (res.success && res.data) {
			commit('setBrandList', res.data);
		}
	},
	async getCateParamAction({
		commit,
		state
	}, pload) {
		const res = await getCateParam(pload);
		if (res.success && res.data) {
			const tmpArray = res.data || [];
			const goodsArgs = state.proInfo.parameterValues;
			tmpArray.forEach(item1 => {
				const parameters = item1.parameters || [];
				parameters.forEach(item2 => {
					item2.parameterId = item2.id;
					if (goodsArgs && goodsArgs.length) {
						const target = goodsArgs.find(g => g.parameterId === item2.id);
						if (target && target.parameterValue) {
							item2.parameterValue = target.parameterValue;
						}
					} else {
						item2.parameterValue = null;
					}

				})
			})
			commit('setCateParam', tmpArray);
		}
	}
}

const mutations = {
	setProInfo(state, data) {
		state.proInfo = data;
	},
	setCateList(state, data) {
		state.cateList = data;
	},
	setBrandList(state, data) {
		state.brandList = data;
	},
	setCateParam(state, data) {
		state.cateParam = data;
	},
	setSpecInfo(state, data) {
		state.specInfo = data;
	},
	setProImgs(state, data){
		state.proImgs = data;
	}
}
export default {
	namespaced: true,
	state,
	actions,
	mutations
}